/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.controllers;

import com.ntb.common.PaginationUtil;
import com.ntb.common.SecuredAction;
import com.ntb.controllers.forms.FlatForm;
import com.ntb.entities.Buildings;
import com.ntb.entities.Flats;
import com.ntb.models.BuildingStatusDAO;
import com.ntb.models.BuildingTypesDAO;
import com.ntb.models.BuildingsDAO;
import com.ntb.models.FlatsDAO;
import com.ntb.models.impl.BuildingStatusDAOImpl;
import com.ntb.models.impl.BuildingTypesDAOImpl;
import com.ntb.models.impl.BuildingsDAOImpl;
import com.ntb.models.impl.FlatsDAOImpl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thinh Hung
 */
public class FlatAction extends SecuredAction {

    private List<String> errorMessages = new ArrayList();
    private List<String> successMessages = new ArrayList();

    @Override
    public ActionForward ntbExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

        ActionForward forward = mapping.getInputForward();
        FlatForm flatForm = (FlatForm) form;
        FlatsDAO flatDao = new FlatsDAOImpl();
        String action = flatForm.getAction();

        errorMessages = new ArrayList();
        successMessages = new ArrayList();


        if ("selectBuilding".equalsIgnoreCase(action)) {
            forward = selectBuilding(request, flatForm, mapping);
        } else if ("save".equalsIgnoreCase(action)) {
            // Save

            forward = updateFlat(flatForm, flatDao, request, mapping);
            if (forward == null) {
                forward = viewFlat(flatDao, flatForm, request, mapping);
            }
        } else if ("save & exit".equalsIgnoreCase(action)) {
            // Save & Back to list

            forward = updateFlat(flatForm, flatDao, request, mapping);
            forward = forward == null ? mapping.findForward("flatListing") : forward;
        } else if ("edit".equalsIgnoreCase(action)) {
            // Show Edit Page

            forward = editFlat(flatDao, flatForm, request, mapping);
        } else if (flatForm.getFlatID() > 0) {
            // Show Detail Page

            forward = viewFlat(flatDao, flatForm, request, mapping);
        } else {
            // Show Add Page

            forward = add(flatDao, flatForm, request, mapping);
        }

        request.setAttribute("errorMessages", errorMessages);
        request.setAttribute("successMessages", successMessages);

        return forward;
    }

    /**
     * Load Add Page
     * 
     * @param request
     * @param flatForm
     */
    private ActionForward add(FlatsDAO flatDao, FlatForm flatForm, HttpServletRequest request, ActionMapping mapping) {
        BuildingsDAO buildingDao = new BuildingsDAOImpl();
        if (buildingDao.checkExist(flatForm.getBuildingID())) {

            request.setAttribute("building", buildingDao.getRow(flatForm.getBuildingID()));

            flatForm.setFlatID(0);
            return mapping.getInputForward();
        } else {
            request.setAttribute("Please select a buildling when add the flat.", this);
            return mapping.findForward("flatListing");
        }
    }

    /**
     * Load Edit Flat Page
     * 
     * @param flatDao
     * @param flatForm
     * @param request
     * @param mapping
     * @return
     */
    private ActionForward editFlat(FlatsDAO flatDao, FlatForm flatForm, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Flats flat = flatDao.getRow(flatForm.getFlatID());

        BuildingsDAO buildingDao = new BuildingsDAOImpl();
        request.setAttribute("building", buildingDao.getRow(flat.getBuildingID()));

        flatForm.setFlatID(flat.getFlatID());
        flatForm.setFlatName(flat.getFlatName());
        flatForm.setFloorNumber(flat.getFloorNumber() + "");
        flatForm.setArea(flat.getArea() + "");
        flatForm.setDescription(flat.getDescription());

        forward = mapping.findForward("flatEdit");
        return forward;
    }

    /**
     * select building
     * @param request
     * @param flatForm
     * @param mapping
     * @return
     */
    private ActionForward selectBuilding(HttpServletRequest request, FlatForm flatForm, ActionMapping mapping) {
        ActionForward forward;
        BuildingsDAO buildingDAO = new BuildingsDAOImpl();
        BuildingTypesDAO typeDao = new BuildingTypesDAOImpl();
        request.setAttribute("buildingTypeList", typeDao.getList());

        BuildingStatusDAO statusDao = new BuildingStatusDAOImpl();
        request.setAttribute("statusList", statusDao.getStatusTable());

        String baseUrl = request.getRequestURI() + "?action=selectBuilding&amp;";

        String buildingId = null;
        String buildingName = null;
        String landId = null;
        int buildingTypeId = -1;
        int floorFrom = -1;
        int floorTo = -1;
        int roomFrom = -1;
        int roomTo = -1;
        String constructedDateFrom = null;
        String constructedDateTo = null;
        String status = null;

        int page = -1;

        buildingId = flatForm.getId();
        buildingId = "".equals(buildingId) ? null : buildingId;
        if (buildingId != null) {
            baseUrl += "id=" + buildingId + "&amp;";
        }

        buildingName = flatForm.getName();
        buildingName = "".equals(buildingName) ? null : buildingName;
        if (buildingName != null) {
            baseUrl += "name=" + buildingName + "&amp;";
        }

        landId = flatForm.getLand();
        landId = "".equals(landId) ? null : landId;
        if (landId != null) {
            baseUrl += "land=" + landId + "&amp;";
        }

        buildingTypeId = flatForm.getType();
        if (buildingTypeId > 0) {
            baseUrl += "type=" + buildingTypeId + "&amp;";
        } else {
            buildingTypeId = -1;
        }

        try {
            floorFrom = Integer.parseInt(flatForm.getFloorF());
        } catch (Exception e) {
        }
        if (floorFrom > 0) {
            baseUrl += "floorF=" + floorFrom + "&amp;";
        } else {
            floorFrom = -1;
        }

        try {
            floorTo = Integer.parseInt(flatForm.getFloorT());
        } catch (Exception e) {
        }
        if (floorTo > 0) {
            baseUrl += "floorT=" + floorTo + "&amp;";
        } else {
            floorTo = -1;
        }

        try {
            roomFrom = Integer.parseInt(flatForm.getRoomF());
        } catch (Exception e) {
        }
        if (roomFrom > 0) {
            baseUrl += "roomF=" + roomFrom + "&amp;";
        } else {
            roomFrom = -1;
        }

        try {
            roomTo = Integer.parseInt(flatForm.getRoomT());
        } catch (Exception e) {
        }
        if (roomTo > 0) {
            baseUrl += "roomT=" + roomTo + "&amp;";
        } else {
            roomTo = -1;
        }


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            df.parse(flatForm.getDateF());
            constructedDateFrom = flatForm.getDateF();
        } catch (Exception ex) {
            constructedDateFrom = null;
        }
        if (constructedDateFrom != null) {
            baseUrl += "dateF=" + constructedDateFrom + "&amp;";
        }

        try {
            df.parse(flatForm.getDateT());
            constructedDateTo = flatForm.getDateT();
        } catch (Exception ex) {
            constructedDateTo = null;
        }
        if (constructedDateTo != null) {
            baseUrl += "dateT=" + constructedDateTo + "&amp;";
        }

        status = flatForm.getStatus();
        status = "".equals(status) ? null : status;
        if (status != null) {
            baseUrl += "status=" + status + "&amp;";
        }

        try {
            int i = Integer.parseInt(request.getParameter("page"));
            page = i > 1 ? i : 1;
        } catch (Exception ex) {
        }

        Iterator<Buildings> buildingList = buildingDAO.getList(buildingId, buildingName, landId, buildingTypeId, floorFrom, floorTo, roomFrom, roomTo, constructedDateFrom, constructedDateTo, status, page);
        request.setAttribute("buildingList", buildingList);

        PaginationUtil paginationUtil = new PaginationUtil();
        paginationUtil.setBaseUrl(baseUrl);
        paginationUtil.setNumPages(buildingDAO.getPageCount(buildingId, buildingName, landId, buildingTypeId, floorFrom, floorTo, roomFrom, roomTo, constructedDateFrom, constructedDateTo, status));
        paginationUtil.setCurPage(page);
        request.setAttribute("pagination", paginationUtil.createLinks());
        forward = mapping.findForward("flatSelectBuilding");
        return forward;
    }

    /**
     * Update Flat
     * 
     * @param flatForm
     * @param flatDao
     * @param mapping
     * @return
     */
    private ActionForward updateFlat(FlatForm flatForm, FlatsDAO flatDao, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Flats flat = new Flats();

        int buildingId = flatForm.getBuildingID();

        BuildingsDAO buildingDao = new BuildingsDAOImpl();



        int floorNumber = 0;
        try {
            floorNumber = Integer.parseInt(flatForm.getFloorNumber());
        } catch (Exception ex) {
        }

        int area = 0;
        try {
            area = Integer.parseInt(flatForm.getArea());
        } catch (Exception ex) {
        }

        flat.setFlatID(flatForm.getFlatID());
        flat.setFlatName(flatForm.getFlatName());
        flat.setBuildingID(buildingId);
        flat.setFloorNumber(floorNumber);
        flat.setArea(area);
        flat.setDescription(flatForm.getDescription());

        if (flat.getFlatID() > 0) {
            Flats temp = flatDao.getRow(flat.getFlatID());
            if (temp == null) {
                errorMessages.add("Flat not found!");
                forward = mapping.findForward("flatListing");
            } else {
                flatDao.update(flat);
                successMessages.add("The flat \"" + flat.getFlatID() + "\" has been saved.");
                return null;
            }
        } else {
            if (!buildingDao.checkExist(buildingId)) {
                errorMessages.add("The building does not exits. Please check the building and try again!");
                forward = add(flatDao, flatForm, request, mapping);
            } else {
                flatDao.add(flat);
                successMessages.add("The new flat has been added.");
                forward = mapping.findForward("flatListing");
            }
        }
        return forward;
    }

    /**
     * Load Detail Page
     * 
     * @param flatDao
     * @param flatForm
     * @param request
     * @param mapping
     * @return
     */
    private ActionForward viewFlat(
            FlatsDAO flatDao, FlatForm flatForm, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Flats flat = flatDao.getRow(flatForm.getFlatID());
        request.setAttribute("flat", flat);

        BuildingsDAO buildingDao = new BuildingsDAOImpl();
        request.setAttribute("building", buildingDao.getRow(flat.getBuildingID()));

        forward =
                mapping.findForward("flatDetail");
        return forward;
    }
}